<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <PageTools>
          <template #left>
            <span>总数:{{ total }}</span>
          </template>
          <template #rigth>
            <el-button round size="small" type="warning" @click="$router.push('/employees/import')">导入Excel</el-button>
            <el-button v-allow="'export_excel'" round size="small" type="danger" @click.native="handleDownload">导出Excel</el-button>
            <el-button round size="small" type="primary" @click="showDialog=true">新增员工</el-button>
          </template>
        </PageTools>
      </el-card>
      <el-card style="margin-top:20px">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <!-- <img class="avatar" :src="row.staffPhoto" alt=""> -->
              <ImageHolder :src="row.staffPhoto" class="avatar" />
            </template>

          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              {{ formmateEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间">
            <template v-slot="{ row }">
              {{ formDataTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button size="small" type="text" @click="$router.push('/employees/detail/' + row.id)">查看</el-button>
              <el-button size="small" type="text" @click="hassign(row.id)">分配角色</el-button>
              <el-button size="small" type="text" @click="hdel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页功能 -->
        <div style="height: 60px; margin-top: 20px">

          <el-pagination
            :current-page="q.page"
            :page-sizes="[10, 15, 20, 30]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      width="45%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <empDialog v-if="showDialog" @success="hSuccess" @close="showDialog=false" />

    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="showDialogRole"
      width="45%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <assignRole v-if="showDialogRole" :id="curId" @close="showDialogRole=false" />

    </el-dialog>
  </div>
</template>
<script>
// 导入员工文件
import Employment from '@/constant/employees'
import { delEmployeesList, getEmployeesList } from '@/api/employees'
import empDialog from './empDialog.vue'
import assignRole from './assignRole.vue'
import dayjs from 'dayjs'
// 定义聘用优化代码
const obj = {}
Employment.hireType.forEach(item => {
  obj[item.id] = item.value
})
export default {
  components: { empDialog, assignRole },
  data() {
    return {
      showDialogRole: false,
      employees: [],
      q: {
        page: 1,
        size: 10
      },
      total: 0,
      showDialog: false,
      curId: ''
    }
  },
  created() {
    // 获取员工信息列表
    this.loadEmployees()
  },
  methods: {
    // 发送请求获取员工信息列表
    async  loadEmployees() {
      const res = await getEmployeesList(this.q)
      this.employees = res.data.rows
      this.total = res.data.total
    },
    // 定义聘用形式
    // 导入employees.js文件。调用里面的封装的信息
    formmateEmployment(code) {
      // const result = Employment.hireType.find(item => item.id === code)
      // if (result) {
      //   return result.value
      // } else {
      //   return '未知'
      // }
      return obj[code]
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    handleSizeChange(size) {
      this.size = size
      this.loadEmployees()
    },
    // 删除功能实现
    async hdel(id) {
      // 提醒用户是否确认删除
      try {
        await this.$confirm('真的要删除吗？嘤嘤嘤', '提示', { type: 'warning' })
        // 发送请求。再API中封装请求接口
        const res = await delEmployeesList(id)
        this.$message.success(res.message)
        if (this.employees.length === 1 && this.q.page > 1) this.q.page--
        this.loadEmployees()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    // 关闭弹框，重新获取列表
    hSuccess() {
      this.showDialog = false
      // 判断最后一页是不是满了，如果满了就自动跳转到后一页
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    // 处理时间格式
    formDataTime(data) {
      return dayjs(data).format('YYYY-MM-DD')
    },
    // 导出
    async handleDownload() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 发送请求
      const res = await getEmployeesList({ page: 1, size: this.total })
      const list = res.data.rows
      const first = list[0]
      if (!first) return
      const header = Object.keys(first).map(item => {
        return mapInfo[item]
      })
      const data = list.map(item => {
        const enkey = item['formOfEmployment']
        item['formOfEmployment'] = obj[enkey]
        return Object.values(item)
      })
      const excel = await import('@/vendor/Export2Excel')

      excel.export_json_to_excel({
        header,
        data,
        filename: '员工数据',
        autoWidth: true,
        bookType: 'xlsx'
      })
    },
    // 分配角色
    hassign(id) {
      this.curId = id
      this.showDialogRole = true
    }
  }
}
</script>
<style lang="scss" scoped>
  .avatar{
      width: 50px;
      height: 50px;
  }
  .el-pagination{
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .avatar{
    width: 50px;
    height: 50px;
  }
</style>
